<?php
namespace app\v1_0\controller\company;

use app\common\model\CompanyStructure;
use think\Db;
use think\Exception;

class Structure extends \app\v1_0\controller\common\Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->checkLogin(1);
        $this->interceptCompanyProfile();
    }

    /**
     * 总编制
     */
    public function makeCompanyScopeCount($pid,$Scope){

        if($pid == 0){
            $structure = model('CompanyStructure')
                ->where(['p_id'=>$pid])
                ->find();
            $pid = null;
        }else{
            $structure = model('CompanyStructure')
                ->where(['id'=>$pid])
                ->find();
            $pid = $structure->p_id == 0 ? null :$structure->p_id;
        }

        $structure->scope += intval($Scope);
        $structure->update_time = date('Y-m-d H:i:s');
        $structure->save();
        if($pid === null){
            return true;
        } else{
            return $this->makeCompanyScopeCount($pid,$Scope);
        }

    }

    /**
     * 总员工总人数
     */
    public function makeCompanyCurrentNumCount($pid,$current_num){

        if($pid == 0){
            $structure = model('CompanyStructure')
                ->where(['p_id'=>$pid])
                ->find();
            $pid = null;
        }else{
            $structure = model('CompanyStructure')
                ->where(['id'=>$pid])
                ->find();
            $pid = $structure->p_id == 0 ? null :$structure->p_id;
        }

        $structure->current_num += intval($current_num);
        $vacancy = $structure->scope - $structure->current_num;
        $structure->vacancy = $vacancy < 0 ? 0 :$vacancy; //缺
        $structure->over_capacity = $vacancy < 0 ? ($structure->current_num - $structure->scope) :0;//超
        $structure->update_time = date('Y-m-d H:i:s');
        $structure->save();
        if($pid === null){
            return true;
        } else{
            return $this->makeCompanyCurrentNumCount($pid,$current_num);
        }

    }
    /**
     * 员工总人数
     */
    public function makeCompanyCurrentNum($p_id,$num){
        Db::startTrans();

        try {

            $this->makeCompanyCurrentNumCount($p_id,$num);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollBack();
            return false;
        }
    }

    public function makeCompany()
    {
        $profile = $this->company_profile;
        $structure_p0 = Db::table(config('database.prefix') . 'company_structure')
            ->where(['com_id'=>$profile->id,'type'=>1,'name'=>$profile->companyname])
            ->find();

        if(!$structure_p0){
            Db::table(config('database.prefix') . 'company_structure')->where(['com_id'=>$profile->id])->delete();
            $contact = Db::table(config('database.prefix') . 'company_contact')
                ->where(['comid'=>$profile->id])
                ->value('contact');
            $input = [
                'com_id' => $profile->id,
                'name' => $profile->companyname,
                'type' => 1,
                'scope' => 0,
                'current_num' => 0,//TODO:添加员工数据
                'vacancy' => 0, //TODO:缺 人数
                'over_capacity' => 0, //TODO:超 人数
                'kahuna' => $contact,
                'p_id' => 0,
                'leader' => null,
                'enable_date' => date('Y-m-d',$profile->addtime),
            ];

            $input['create_time'] = date('Y-m-d H:i:s');
            $input['update_time'] = $input['create_time'];
            $input['update_at'] = $this->userinfo->uid;
            $input['create_at'] = $this->userinfo->uid;
             model('CompanyStructure')
                ->allowField(true)
                ->save($input);
            $id = model('CompanyStructure')->id;
        }
        else{
            $id = $structure_p0['id'];
        }
        return $id;
    }

    public function index()
    {


        $profile = $this->company_profile;
        $this->makeCompany();

        $filterDepartment = input('get.filterDepartment/a', []);
        $query = CompanyStructure::where('com_id', 'eq', $profile->id)
            ->field('id,p_id,name,kahuna,leader,type,scope,current_num');

        if (!empty($filterDepartment)) {
            $query->where(['leader' => ['like', implode(',', $filterDepartment) . '%']]);
            $query->whereor(['id' => current($filterDepartment)]);
        }

        $CompanyStructure = $query->select();

        $leaders = array_column_G($CompanyStructure,['p_id','kahuna'],'p_id');

        foreach ($CompanyStructure as $key => $item) {
            $item = $item->toArray();

            $item['current_num'] = max($item['current_num'], 0);
//            $CompanyStructure[$key]['leader'] = !empty($p_item) ? $p_item['kahuna'] : $item['kahuna'];
            $item['leader'] = $item['p_id']?($leaders[$item['p_id']]['kahuna']??''):'';
            $item['kahuna'] = $item['p_id']?$item['kahuna']:'';
//            $item['leader'] = $leaders[$item['p_id']]['kahuna']??'';
            $CompanyStructure[$key] = $item;
        }
        $data = $this->generateTree($CompanyStructure);
        $data = $this->resetKeys($data);
        $this->calScope($data);

        $this->ajaxReturn(200, '获取到数据', $data);

    }

    public function filterCompanyData()
    {
        $company = Db::table(config('database.prefix') . 'company_structure')
            ->alias('cs')
            ->field("id as `value`, `name` as `label`,p_id")
            ->where(['com_id' => $this->company_profile['id']])
            ->where(['type' => 1])
            ->group('id')
            ->select();
        $data = $this->generateTree($company,'value');
        $default = Db::table(config('database.prefix') . 'company_structure')
            ->where(['com_id'=>$this->company_profile->id,'type'=>1,'p_id'=>0])
            ->value('id');
        //print_r($data);
        $data['items'] = $this->resetKeys($data);
        $data['default'] = [$default];
        $this->ajaxReturn(200, '获取到数据',$data);
    }

    public function filterDepartmentData()
    {
        $pid=input('get.id/d', 0, 'intval');
        //$where = ['type' => 2];
        $where = ['com_id'=>$this->company_profile['id']];
        if($pid){
            $where['p_id'] = $pid;
        }
        $department = Db::table(config('database.prefix') . 'company_structure')
            ->alias('cs')
            ->field("id as `value`, `name` as `label`,p_id")
            ->where('p_id','>',0)
            ->where($where)
            ->group('id')
            ->select();
        $data = $this->generateTree($department,'value');
        $data = $this->resetKeys($data);

        $this->ajaxReturn(200, '获取到数据', $data);
    }


    public function filterDepartmentData_backup()
    {
        $pid=input('get.id/d', 0, 'intval');
        $where = ['type' => 2];
        if($pid){
            $where['p_id'] = $pid;
        }
        $department = Db::table(config('database.prefix') . 'company_structure')
            ->alias('cs')
            ->field("id as `value`, `name` as `label`,p_id")
            ->where($where)
            ->group('id')
            ->select();
        $data = $this->generateTree($department,'value');
        $data = $this->resetKeys($data);

        $this->ajaxReturn(200, '获取到数据', $data);
    }


    public function editInfo()
    {
        $this->interceptCompanyProfile();
        $id=input('get.id/d', 0, 'intval');
        if(!$id){
            $this->ajaxReturn(500, '缺少参数');
        }
        $CompanyStructure = model('CompanyStructure')
            ->alias('cs')
            ->field('name,type,scope,kahuna,leader,enable_date')
            ->where(['id' =>$id])
            ->find();
        $this->ajaxReturn(200, '获取成功',$CompanyStructure);
    }
    public function addInfo()
    {
        $this->interceptCompanyProfile();

        $defaultLeader = model('CompanyStructure')
            ->alias('cs')
            ->field('name,type,scope,kahuna,leader,enable_date')
            ->where(['com_id' =>$this->company_profile->id,'p_id'=>0])
            ->value('id');

        $info['defaultLeader'] = [$defaultLeader];
        $this->ajaxReturn(200, '获取成功',$info);
    }

    public function save()
    {

        $this->interceptCompanyProfile();
        $profile = $this->company_profile;
        $id=input('post.id/d', 0, 'intval');
        $leader = input('post.leader/a');
        $p_id = empty($leader) ? 0 : end($leader);
        $leader = empty($leader) ? [] : $leader;
        $input = [
            'com_id' => $profile->id,
            'name' => input('post.name/s', '', 'trim,badword_filter'),
            'type' => input('post.type/d', 1, 'intval'),
            'scope' => input('post.scope/d', 0, 'intval'),
//            'current_num' => input('post.current_num/d', 0, 'intval'),//TODO:添加员工数据
//            'vacancy' => input('post.vacancy/d', 0, 'intval'), //TODO:缺 人数
//            'over_capacity' => input('post.over_capacity/d', 0, 'intval'), //TODO:超 人数
            'kahuna' => input('post.kahuna/s', "", 'trim,badword_filter'),
            'p_id' => $p_id,
            'leader' => implode(',',$leader),
            'enable_date' => input('post.enable_date/s', null),
        ];

        $input['scope'] = $input['scope'] < 0 ? 0 : $input['scope'];
        if($id){
            $input['update_time'] = date('Y-m-d H:i:s');
            $input['update_at'] = $this->userinfo->uid;
            $CompanyStructure = model('CompanyStructure')->where('id',$id)->find();
            $scope = $CompanyStructure->scope;
            $result =$CompanyStructure->allowField(true)->save($input);
            if($result){
                $this->makeCompanyScopeCount($p_id, $input['scope'] - $scope);
            }

        }else{
            $input['create_time'] = date('Y-m-d H:i:s');
            $input['update_time'] = $input['create_time'];
            $input['update_at'] = $this->userinfo->uid;
            $input['create_at'] = $this->userinfo->uid;
            $result = model('CompanyStructure')
                 ->allowField(true)
                ->save($input);
            if($result){
                $id = model('CompanyStructure')->id;
                $this->makeCompanyScopeCount($p_id,$input['scope']);
            }

        }
        $this->makeCompanyCurrentNum($id, 0);
        $this->ajaxReturn(200, '保存成功', [
            'id' => $id,
            'result' => $result,
        ]);

    }

    public function maxScope(){
        $ids=input('get.leader/a');

        if(empty($ids)){
            $this->ajaxReturn(500, '缺少参数');
        }
        $id= end($ids);
        $c_scope = Db::table(config('database.prefix') . 'company_structure')
            ->where('id',$id)
            ->value('scope');
        $scope = Db::table(config('database.prefix') . 'company_structure')
            ->where('p_id',$id)
            ->sum('scope');

        $data['max'] = $c_scope - $scope;
        $data['max'] = $data['max'] >0 ? $data['max'] : 0 ;
        $this->ajaxReturn(200, '获取到数据',$data);

    }
    public function leaders()
    {
        $this->interceptCompanyProfile();
        $type=input('get.type/d', 0, 'intval');
        $profile = $this->company_profile;
        $where = ['com_id' => $profile->id];
        if($type == 1){
            $where['type'] = 1;
        }
        $CompanyStructure = Db::table(config('database.prefix') . 'company_structure')
            ->alias('cs')
            ->field("id as `value`, `name` as `label`,p_id")
            ->where($where)
            ->group('id')
            ->select();

        $data = $this->generateTree($CompanyStructure,'value');
        $data = $this->resetKeys($data);

        $this->ajaxReturn(200, '获取到数据',$data);

    }
    public function delBatch(){
        $ids=input('post.ids/a');
        if(empty($ids))
        {
            $this->ajaxReturn(500, '缺少参数');
        }
        foreach ($ids as $id)
        {
            $this->del($id,false);
        }
        $this->ajaxReturn(200, '删除成功');
    }
    public function dels($pid){
        static $ids =[];
        $column_ids = model('CompanyStructure')->where('p_id', 'in', $pid)->column('id');
        if(empty($column_ids))
        {
            return $ids;
        }
        $ids = array_merge($ids,$column_ids);
        foreach ($column_ids as $p_id)
        {
            return $this->dels($p_id);
        }
    }
    public function del($id = null,$isReturn=true)
    {
        $id=$id ? $id : input('post.id/d', 0, 'intval');

        if(!$id){
           return !$isReturn?false: $this->ajaxReturn(500, '缺少参数');
        }
        \think\Db::startTrans();
        try {
           $CompanyStructure = model('CompanyStructure')->where(['id'=> array('in',$id)])->find();
            if($CompanyStructure->p_id == 0){
                return $this->ajaxReturn(500, '第一级公司不允许删除');
            }
            $p_id = $CompanyStructure->p_id;
            $scopes = model('CompanyStructure')->where(['id'=> array('in',$id)])->sum('scope');
            $current_num = model('CompanyStructure')->where(['id'=> array('in',$id)])->sum('current_num');
            $ids = $this->dels($id);
            array_push($ids,$id);
            model('CompanyStructure')->where(['id'=> array('in',$ids)])->delete();

            $this->makeCompanyScopeCount($p_id,-$scopes);
            $this->makeCompanyCurrentNumCount($p_id,-$current_num);

            \think\Db::commit();
        } catch (\Exception $e) {
            \think\Db::rollBack();
            return !$isReturn? false: $this->ajaxReturn(500, $e->getMessage());
        }
        return !$isReturn? true: $this->ajaxReturn(200, '删除成功');

    }

    private function calScope(&$data){
        $result = [];
        foreach ($data as &$value){
            if(!empty($value['children'])){
                $result += $this->calScope($value['children']);
                $value['scope'] = $result[$value['id']]['scope']??0;
            }
            if($value['p_id'] > 0){
                if(empty($result[$value['p_id']])){
                    $result[$value['p_id']]['scope'] = 0;
                }
                $result[$value['p_id']]['scope'] += $value['scope'];
            }

        }
        return $result;
    }

}
